#! -*- coding: utf-8 -*-
from SimpleXMLRPCServer import SimpleXMLRPCServer
from core import Open4D
import SocketServer

class AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer):
    pass

class AsyncXMLRPC4DServer(AsyncXMLRPCServer):
    def __init__(self,addr=("", 8000),logRequests=False):
        AsyncXMLRPCServer.__init__(self,addr,logRequests=logRequests,allow_none=True)#,encoding='cp1252')
        self.register_introspection_functions()

class XMLRPC4DServer(SimpleXMLRPCServer):
    def __init__(self,addr=("", 8000),logRequests=False):
        SimpleXMLRPCServer.__init__(self,addr,logRequests=logRequests,allow_none=True)#,encoding='cp1252')

class Open4DDispatch(object):
    def __init__(self):
        self.funcs = {}

    def _listMethods(self):
        return dir(self)

    def _dispatch(self,method,params):
        methd = method.split('.',1)
        if len(methd) == 1:
            func = getattr(self,method)
            return func(*params)
        else:
            funcs = self.funcs.get(methd[0])
            return funcs._dispatch(methd[1],params)

    def test(self):
        return 'ok'

class Open4DFunc(object):
    def __init__(self,networkcomponent=2,find4dserver='',username='',password=''):
        self.networkcomponent = networkcomponent
        self.find4dserver = find4dserver
        self.username = username
        self.password = password
        self.client4d = Open4D()
        self.client4d.InitNetworkComponent(networkcomponent)
        if not find4dserver:
            self.client4d.Select4DServer()
        else:
            self.client4d.Find4DServer(find4dserver)

    def _listMethods(self):
        return dir(self)

    def _connect(self):
        client = self.client4d.new_process()
        err = client.connect(self.username,self.password)
        if err:
            raise Exception('Connect error')
        return client

    def _dispatch(self, method, params):
        if method[0] == '_':
            raise Exception('method "%s" is not supported' % method)
        func = getattr(self,method)
        client4d = self._connect()
        try:
            res = func(client4d,*params)
        finally:
            client4d.Close4DConnection()
        return res

    def test(self,client4d):
        return client4d.Server_CurrentDateTime()

if __name__ == '__main__':

    # Create server
    server = XMLRPC4DServer(logRequests=True)

    a = Open4DDispatch()
    a.funcs['server4d'] = Open4DFunc(2,'JASV04','Super_Utilisateur','test')
    server.register_instance(a)

    # Run the server's main loop
    print 'Lancement du serveur XML-RPC.'
    server.serve_forever()

